package cn.gdrj.est.service.impl;

import cn.gdrj.est.constants.Constants;
import cn.gdrj.est.entity.Users;
import cn.gdrj.est.service.TokenService;
import cn.gdrj.est.vo.TokenVO;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public TokenVO generateToken(Users users) {
        TokenVO tokenVO= new TokenVO();
        // 生成token
        String uuid = UUID.fastUUID().toString(true);
        tokenVO.setToken(uuid);
        return tokenVO;
    }

    @Override
    public void saveToken(String token, Users users) {
        // 保存会话信息
        ValueOperations<String, String> valueOperations =
                redisTemplate.opsForValue();
        String usersJsonString = JSON.toJSONString(users);
        valueOperations.set(Constants.Redis.PREFIX_TOKEN+token,
                usersJsonString,
                60,
                TimeUnit.MINUTES);
    }

    @Override
    public Users getUserInfoByToken(String token) {
        ValueOperations<String, String> valueOperations =
                redisTemplate.opsForValue();
        String usersJsonString = valueOperations
                .get(Constants.Redis.PREFIX_TOKEN + token);
        if(usersJsonString == null){
            return null;
        }
        Users users = JSON.parseObject(usersJsonString, Users.class);
        return users;
    }

    @Override
    public void removeToken(String token) {
        redisTemplate.delete(Constants.Redis.PREFIX_TOKEN + token);
    }
}
